package com.mehdiuz.backend.role.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mehdiuz.backend.commons.utils.Result;
import com.mehdiuz.backend.role.entity.Role;
import com.mehdiuz.backend.role.entity.User;
import com.mehdiuz.backend.role.entity.UserRole;
import com.mehdiuz.backend.role.entity.vo.RoleBackVo;
import com.mehdiuz.backend.role.entity.vo.UserSearchVo;
import com.mehdiuz.backend.role.service.OSSService;
import com.mehdiuz.backend.role.service.RoleService;
import com.mehdiuz.backend.role.service.UserRoleService;
import com.mehdiuz.backend.role.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/system/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OSSService ossService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @PostMapping("getUserRole")
    @ApiOperation(value = "查询当前用户的角色")
    @PreAuthorize("hasAuthority('bnt.role.grant')")
    public Result<List<RoleBackVo>> getUserRole(@RequestBody User user){
        List<UserRole> userRoleList = userRoleService.getBaseMapper().selectList(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
        List<Role> roles = roleService.getBaseMapper().selectList(new QueryWrapper<Role>());
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<RoleBackVo> roleBackVos = new ArrayList<>();
        roles.forEach(role->{
            RoleBackVo roleBackVo = new RoleBackVo();
            BeanUtils.copyProperties(role,roleBackVo);
            if(roleIds.contains(role.getId())){
                roleBackVo.setIsSelect(true);
            }else {
                roleBackVo.setIsSelect(false);
            }
            roleBackVos.add(roleBackVo);
        });

        return Result.ok(roleBackVos);
    }

    @PostMapping("userGrant/{userId}")
    @ApiOperation(value = "给当前用户进行角色分配")
    @PreAuthorize("hasAuthority('bnt.role.grant')")
    public Result<Boolean> userGrant(@PathVariable Long userId,@RequestBody List<UserRole> userRoles){
        List<UserRole> userRoleList = userRoleService.getBaseMapper().selectList(new QueryWrapper<UserRole>().eq("user_id", userId).eq("is_deleted",0));
        AtomicBoolean b = new AtomicBoolean(false);
        if(userRoleList.size() == 0){
            b.set(userRoleService.saveBatch(userRoles));
            if(b.get()){
                return Result.ok(b.get());
            }else {
                return Result.fail();
            }
        }else {
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            //和传入相比多出来的删掉
            userRoleList.forEach(userRole -> {
                if(!roleIds.contains(userRole.getRoleId())){
                    b.set(userRoleService.removeById(userRole.getId()));
                }
            });
            //和传入相比一样的不用处理
            //和传入相比少的做插入
            userRoleList.forEach(userRole->{
                userRoles.removeIf(role->role.getUserId().equals(userRole.getUserId()) && role.getRoleId().equals(userRole.getRoleId()));
            });

            if(userRoles.size()>0){
                b.set(userRoleService.saveBatch(userRoles));
            }
            if(b.get()){
                return Result.ok(b.get());
            }else {
                return Result.fail();
            }
        }
    }

    @GetMapping("getSign")
    @ApiOperation(value = "获取oss签名")
    public Result<Map<String,Object>> getSign(){
        Map<String, Object> ossSign = ossService.getOssSign();
        return Result.ok(ossSign);
    }

    @PostMapping("/{page}/{limit}")
    @ApiOperation(value = "用户分页查询")
    @PreAuthorize("hasAuthority('bnt.user.list')")
    public Result<IPage<User>> index(@PathVariable long page,@PathVariable long limit, @RequestBody UserSearchVo user){
        Page<User> pageParam = new Page<>(page,limit);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(user.getUserName())){
            queryWrapper.like("username",user.getUserName());
        }
        if(StringUtils.isNotBlank(user.getName())){
            queryWrapper.like("name",user.getName());
        }
        if(null != user.getCreateTime()){
            if(user.getCreateTime().size() == 2){
                queryWrapper.between("create_time",user.getCreateTime().get(0),user.getCreateTime().get(1));
            }
        }
        if(StringUtils.isNotBlank(user.getPhone())){
            queryWrapper.like("phone",user.getPhone());
        }
        if(user.getStatus() != null){
            queryWrapper.eq("status",user.getStatus());
        }
        if(null != user.getUpdateTime()){
            if(user.getUpdateTime().size() == 2){
                queryWrapper.between("update_time",user.getUpdateTime().get(0),user.getUpdateTime().get(1));
            }
        }
        IPage<User> userPage = userService.page(pageParam,queryWrapper);
        return Result.ok(userPage);
    }

    @PostMapping("insertUser")
    @ApiOperation(value = "用户添加")
    @PreAuthorize("hasAuthority('bnt.user.insert')")
    public Result<Boolean> insertUser(@RequestBody User user){
        boolean save = false;
        save = userService.save(user);
        if(save){
            return Result.ok(save);
        }else {
            return Result.fail();
        }
    }

    @PostMapping("updateUser")
    @ApiOperation(value = "用户更新")
    @PreAuthorize("hasAuthority('bnt.user.edit')")
    public Result<Boolean> updateUser(@RequestBody User user){
        boolean update = false;
        update = userService.update(user,new QueryWrapper<User>().eq("id",user.getId()));
        if(update){
            return Result.ok(update);
        }else {
            return Result.fail();
        }
    }

    @PostMapping("deleteUser")
    @ApiOperation(value = "用户批量删除")
    @PreAuthorize("hasAuthority('bnt.user.delete')")
    public Result<Boolean> deleteUser(@RequestBody List<User> users){
        List<Long> idList = users.stream().map(User::getId).collect(Collectors.toList());
        boolean b = false;
        b = userService.removeByIds(idList);
        if(b){
            return Result.ok(b);
        }else {
            return Result.fail();
        }
    }
}
